<template>
  <div id="customizeConfigDiv" class="adminSet">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="200px" class="demo-ruleForm">
      <!--
      <el-form-item label="定制单价" prop="customizePrice">
        <el-input
          v-model="ruleForm.customizePrice"
          type="number"
          oninput="value=value.replace(/[^0-9.]/g,'')"
          class="input_edit"
          style="text-align-last:right"
          placeholder="定制单价"
          v-on:blur="customizePriceCheck()"
        >
          <template slot="prepend">每瓶</template>
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      -->
      <el-form-item label="定制规格" prop="customizeSpec">
        <el-input
          v-model="ruleForm.customizeSpec"
          type="number"
          oninput="value=value.replace(/[^0-9]/g,'')"
          class="input_edit"
          style="text-align-last:right"
          :min="1"
          placeholder="定制规格"
          v-on:blur="customizeSpecCheck()"
        >
          <template slot="prepend">每箱</template>
          <template slot="append">瓶</template>
        </el-input>
      </el-form-item>
      <el-form-item label="最小起订数" prop="minCount">
        <el-input
          v-model="ruleForm.minCount"
          type="number"
          oninput="value=value.replace(/[^0-9]/g,'')"
          class="input_edit"
          style="text-align-last:right"
          :min="5"
          placeholder="最小起订数"
          v-on:blur="minCountCheck()"
        >
          <template slot="append">箱</template>
        </el-input>
      </el-form-item>
      <el-form-item label="定制活动有效期" prop="dateRange">
        <el-date-picker
          v-model="ruleForm.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          :default-time="['00:00:00', '23:59:59']"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="ruleForm.status">
            <el-radio-button label="0">禁用</el-radio-button>
            <el-radio-button label="1">启用</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="定制活动说明" prop="description">
        <el-input
            type="textarea"
            v-model="ruleForm.description"
            placeholder="请输入定制活动说明"
            maxlength="120"
            show-word-limit
            :autosize="{ minRows: 2 }"
            style="width:650px;"
        ></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="24" style="text-align: center;margin-top: 30px">
          <el-button 
            type="info"
            @click="resetForm()" 
            size="mini"
          >取 消</el-button>
          <el-button
            type="primary"
            @click="saveForm()"
            size="mini"
          >保 存</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import {
  queryGoodsCustomizeConfig,
  updateGoodsCustomizeConfig
} from "@/api/goodsCustomize";
import qs from "qs";

const isMoney = function(rule, value, callback) {
  const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
  if (!value) {
    return callback(new Error("金额不能为空"));
  } else if (!reg.test(value)) {
    return callback(new Error("金额格式错误"));
  } else if (value <= 0) {
    return callback(new Error("金额不能小于等于0"));
  } else {
    callback();
  }
};

const isCustomizeSpec = function(rule, value, callback) {
  if ((value == null || value == "") && value != "0") {
    return callback(new Error("数字不能为空"));
  } else if (isNaN(value)) {
    return callback(new Error("数字格式错误"));
  } else if (value < 1) {
    return callback(new Error("定制规格最小为1"));
  } else {
    callback();
  }
};

const isMinCount = function(rule, value, callback) {
  if ((value == null || value == "") && value != "0") {
    return callback(new Error("数字不能为空"));
  } else if (isNaN(value)) {
    return callback(new Error("数字格式错误"));
  } else if (value < 5) {
    return callback(new Error("最小起订数最小为5"));
  } else {
    callback();
  }
};

const isOutTime = function(rule, value, callback) {
  if (value != null && value.length == 2 && value[1] <= curTimeStr()) {
    return callback(new Error("定制活动有效期已过期"));
  }else{
    callback();
  }
};

const curTimeStr = function (){
  var curDate = new Date();
  var year = curDate.getFullYear();
  var month = curDate.getMonth() + 1;
  month = month > 9 ? month : "0" + month;
  var date = curDate.getDate();
  date = date > 9 ? date : "0" + date;
  var hours = curDate.getHours();       //获取当前小时数(0-23)
  hours = hours > 9 ? hours : "0" + hours;
  var minus = curDate.getMinutes();     //获取当前分钟数(0-59)
  minus = minus > 9 ? minus : "0" + minus;
  var secon = curDate.getSeconds();     //获取当前秒数(0-59)
  secon = secon > 9 ? secon : "0" + secon;
  return year + "-" + month + "-" + date + " " + hours + ":" + minus + ":" + secon;
};

export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      ruleForm: {
        uuid: "",
        customizePrice: "",
        customizeSpec: "",
        minCount: "",
        beginTime: "",
        endTime: "",
        status: 0,
        description: "",
        dateRange: "",
      },
      rules: {
        /*
        customizePrice: [
          {
            required: true,
            message: "请输入定制单价",
            trigger: "blur"
          },
          { validator: isMoney, trigger: "blur" }
        ],*/
        customizeSpec: [
          { required: true, message: "请输入规格", trigger: "blur" },
          { validator: isCustomizeSpec, trigger: "blur" }
        ],
        minCount: [
          { required: true, message: "请输入最小起订数", trigger: "blur" },
          { validator: isMinCount, trigger: "blur" }
        ],
        dateRange: [
          { validator: isOutTime, trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.queryGoodsCustomizeConfig();//获取当前定制活动配置信息
  },
  watch: {},
  methods: {
    toPrice(val, type) {
      // 值，符号
      if (val === null || val === undefined || val === "") {
        return "0.00";
      } else {
        var data = Number(val)
          .toFixed(2)
          .split(".");
        var newData = data[0]
          .split("")
          .reverse()
          .join("");
        if (type) {
          return (
            type +
            newData
              .split("")
              .reverse()
              .join("")
              .slice(1) +
            "." +
            data[1]
          );
        } else {
          return (
            newData
              .split("")
              .reverse()
              .join("")
              .slice(0) +
            "." +
            data[1]
          );
        }
      }
    },
    toNumber(val, min) {
      // 值，符号
      if (val === null || val === undefined || val === "") {
        return min;
      } else {
        var val1 =  Number(val).toFixed(0);
        if(val1 < min){
          return min;
        }else{
          return val1;
        }
      }
    },
    //获取当前定制活动配置信息
    queryGoodsCustomizeConfig(){
      queryGoodsCustomizeConfig().then(res => {
        this.ruleForm.uuid = res.result.uuid;
        this.ruleForm.customizePrice = res.result.customizePrice;
        this.ruleForm.customizeSpec = res.result.customizeSpec;
        this.ruleForm.minCount = res.result.minCount;
        this.ruleForm.beginTime = res.result.beginTime;
        this.ruleForm.endTime = res.result.endTime;
        this.ruleForm.status = res.result.status;
        this.ruleForm.description = res.result.description; 
        if(this.ruleForm.beginTime != null && this.ruleForm.endTime != null){
          this.ruleForm.dateRange = [this.ruleForm.beginTime, this.ruleForm.endTime];
        }
      });
    },
    //日期选择
    getNewDatetimeRange(date, fmt){
      alert(date);
    },
    //取消
    resetForm(){
      this.queryGoodsCustomizeConfig();
    },
    //保存
    saveForm(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.ruleForm.dateRange != null && this.ruleForm.dateRange.length == 2) {
            this.ruleForm.beginTime = this.ruleForm.dateRange[0];
            this.ruleForm.endTime = this.ruleForm.dateRange[1];
          }else{
            //this.$message.error("请选择定制活动有效期");
            //return;
            this.ruleForm.beginTime = null;
            this.ruleForm.endTime = null;
          }
          let data = this.ruleForm;
          updateGoodsCustomizeConfig(data).then(res => {
            if(res.code == 1){
                this.$message({
                showClose: true,
                message: res.message,
                type: "success"
              });
            }else{
              this.$message({
                showClose: true,
                message: res.message,
                type: "error"
              });
            }
            this.queryGoodsCustomizeConfig();
          });
        } else {
          return false;
        }
      });
      
    },
    customizePriceCheck(){
      let val = this.ruleForm.customizePrice;
      if (val != null && !isNaN(val)) {
        this.ruleForm.customizePrice = parseFloat(val).toFixed(2);
      }
      return true;
    },
    customizeSpecCheck(){
      let val = this.ruleForm.customizeSpec;
      if (val != null && !isNaN(val)) {
        this.ruleForm.customizeSpec = parseInt(val);
      }
      return true;
    },
    minCountCheck(){
      let val = this.ruleForm.minCount;
      if (val != null && !isNaN(val)) {
        this.ruleForm.minCount = parseInt(val);
      }
      return true;
    }
  }
};
</script>>

<style lang="less" scoped>
.input_edit {
  // position: relative;
  font-size: 14px;
  //display: inline-block;
  width: 300px;
}
#customizeConfigDiv /deep/ input.el-input__inner[type='number']{
  padding:0;
}
</style>
